package com.demo2do.boyle.client.web.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo2do.boyle.client.Constant;
import com.demo2do.boyle.client.handler.ValidateCodeHandler;
import com.demo2do.boyle.client.service.CustomerService;
import com.demo2do.boyle.common.entity.customer.Customer;
import com.demo2do.boyle.common.entity.protocol.sms.SmsType;
import com.demo2do.core.entity.Result;
import com.demo2do.core.utils.JsonUtils;

@Controller
public class ValidateController {

    private static final Logger logger = LoggerFactory.getLogger(ValidateController.class);

    @Autowired
    private ValidateCodeHandler validateCodeHandler;

    @Autowired
    private CustomerService customerService;

    /**
     * 
     * @param phone
     * @return
     */
    @ResponseBody
    @RequestMapping("/register-validate-code")
    public String registerValidateCode(@RequestParam("phone") String phone) {

        Result result = new Result();

        try {

            Customer customer = customerService.loadByMobile(phone);

            if(customer != null) {
                result.fail().message("手机号已注册");
            } else {
                result = validateCodeHandler.sendValidateCode(phone, Constant.MODULE_REGISTER, SmsType.CUSTOMER_REGISTER);
            }

        } catch(Exception e) {

            logger.error("registerValidateCode()", e);
            result.fail().message("验证码获取失败");
        }

        return JsonUtils.toJsonString(result);
    }

    /**
     * 
     * @param phone
     * @return
     */
    @ResponseBody
    @RequestMapping("/forget-password-validate-code")
    public String forgetPasswordValidateCode(@RequestParam("phone") String phone) {

        Result result = new Result();

        try {
            Customer customer = customerService.loadByMobile(phone);

            if(customer == null) {
                result.fail().message("手机号未注册");
            } else {
                result = validateCodeHandler.sendValidateCode(phone, Constant.MODULE_FORGET_PASSWORD, SmsType.CUSTOMER_FORGET_PASSWORD);
            }

        } catch(Exception e) {

            logger.error("forgetPasswordValidateCode()", e);
            result.fail().message("验证码获取失败");
        }

        return JsonUtils.toJsonString(result);
    }

}
